<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>document</title>
    <style>
        #canvas {
            border: 1px dashed red;
        }
    </style>
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<script>
    var canvas = document.querySelector("#canvas");
    var ctx = canvas.getContext("2d");

    //获得画布尺寸
    var casW = canvas.width, casH = canvas.height;

    //绘制坐标系
    var marginTop = 20,
            marginLeft = 20,
            marginRight = 20,
            marginBottom = 20;
    //设置坐标原心
    var x = marginLeft,
            y = casH - marginTop;
    ctx.moveTo(marginLeft, marginTop);
    ctx.lineTo(x, y);
    ctx.lineTo(casW - marginLeft, casH - marginTop);

    ctx.stroke();
    //自定义箭头的宽高
    var arrowWidth = 10,
            arrowHeight = 20;
    ctx.beginPath();//开启新的路径
    //绘制y 轴坐标箭头
    ctx.moveTo(marginLeft, marginTop);
    ctx.lineTo(marginLeft - arrowWidth / 2, marginTop + arrowHeight);
    ctx.lineTo(marginLeft, marginTop + arrowHeight / 2);
    ctx.lineTo(marginLeft + arrowWidth / 2, marginTop + arrowHeight);
    ctx.closePath();
    //绘制x轴坐标箭头
    ctx.moveTo(casW - marginRight, y);
    ctx.lineTo(casW - marginRight - arrowHeight, y - arrowWidth / 2);
    ctx.lineTo(casW - marginRight - arrowHeight / 2, y);
    ctx.lineTo(casW - marginRight - arrowHeight, y + arrowWidth / 2);
    ctx.closePath();
    ctx.fill();

    //准备产生随机数的函数
    function random(min, max) {
        return parseInt((max - min) * Math.random()) + min;
    }

    //产生需要绘制的随机条形数
    var bars = random(4, 10);
    //准备条形图的随机数据
    var datas = [];
    for (var i = 0; i < bars; i++) {
        datas.push(random(50, 379));
    }
    //计算可绘制区域
    var areaW = casW - marginLeft - marginRight,
            areaH = casH - marginTop - marginBottom;
    //计算分配条形宽度
    var distance = areaW / (bars + 1);
    //计算出最高的一个数据并计算对应数据与坐标的比例
    var max = Math.max.apply(null, datas);//方法借用
    //计算显示比例
    var k = areaH / max;

    //开始准备绘图数据
    var newDatas = datas.map(function (v, i) {
        return {
            value: v,
            start: {
                x: x + distance * (i+1),
                y: y
            },
            end: {
                x: x + distance * (i+1),
                y: y - v * k
            }

        }
    });

    //开始绘图
    ctx.beginPath();
    //画点
    newDatas.forEach(function (v) {
        ctx.fillStyle="#000";
        ctx.fillRect(v.start.x-3, v.start.y-6,6,6);
        ctx.fillStyle="red";
        ctx.fillRect(v.end.x-3, v.end.y-3,6,6)

    });
    ctx.fill();

    // 划线
    ctx.beginPath();
    ctx.strokeStyle="blue";
    newDatas.forEach(function(v,i){
        i==0?ctx.moveTo(v.end.x, v.end.y):ctx.lineTo(v.end.x, v.end.y);
    });
    ctx.stroke();

</script>
</body>
</html>